// pages/msgList/msgList.js
const db = wx.cloud.database();
const _ = db.command;
const App = getApp();
var watcher = '';
var sids = [];//会话号数组
var loading=false;
var myOpenid=App.globalData.openid;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sessions: [],
    tabbar: {},
    NoMsg:false,
  },
  onLoad: function (options) {
    App.editTabbar();
    console.log('列表页onLoad');
  },
  onShow: async function () {
    loading=false;
    console.log('列表页onshow');
    //判断先前的watcher是否已关闭
    if(Object.prototype.toString.call(watcher) === '[object Object]') {
          await watcher.close();
          watcher = '';
          console.log('进入列表页时之前列表页的watcher未关闭')
    }
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    setTimeout(this.getSessions, 1000);
    App.editTabbar();
  },
  //获取志愿者的 会话数组
  async getSessions() {
    let res = await db.collection('all_user')
      .where({
        _openid: myOpenid
      })
      .get()
    let len = res.data[0].mySession_ids.length;  
    if(len) {
      this.data.sessions = res.data[0].mySession_ids;
      console.log('该志愿者有会话，会话数组：',this.data.sessions);
      sids = this.data.sessions.map(function (n) { return n.session_id });//从会话数组中提取出会话号
      this.watch();
      if(this.data.NoMsg){
      this.setData({
        NoMsg:false
      })
      }
    } else{
      console.log('该志愿者无会话');
      this.setData({
        NoMsg:true
      })
      wx.showToast({
        title: '没有会话哦',
        icon:'error'
      })
    }
  },
  //监听我的所有项目会话（是否有项目负责人发来新消息）
    watch() {
    console.log('开启消息列表页的会话监听');
    var arr = sids;
    var that = this;
    watcher = 
      db.collection('chat_msg')
        .where({
          session_id: _.in(arr),
        })
        .watch({
          onChange: this.onChange.bind(this),
          onError: function (err) {
            console.log("onError", err);
            if(loading==false){
              wx.hideLoading({
                complete: () => {loading=true},
              })
              }
            wx.showModal({
              title: '提示',
              content: '数据监听失败',
              showCancel:false,
              confirmText:'重新加载',
              success (res) {
                if (res.confirm) {
                  that.onShow();
                } 
              }
            })
          }
        })

  },
  //监听回调函数
  onChange(snapshot) {
    console.log('消息列表页监听回调函数的snapshot', snapshot);
    const sessions = this.data.sessions;
    snapshot.docChanges.forEach(update);//对发生改变的会话记录进行了遍历
    function update(e) {
      const sid = e.doc.session_id;
      const index = sids.indexOf(sid);
      const msg_set = e.doc.msg_set;
      const len = msg_set.length;
      //如果该会话无任何消息，则跳出
      if (len == 0) return;
      const lastMsgTime = msg_set[len - 1].createTimeStamp;
      const leaveTimeStamp = sessions[index].leaveTimeST;
      let unReadNum = 0;
      if ((lastMsgTime > leaveTimeStamp) || (lastMsgTime == leaveTimeStamp)) {
        if (lastMsgTime == leaveTimeStamp) { unReadNum = 1; }
        if (lastMsgTime > leaveTimeStamp) {
          unReadNum = function () {
            let sum = 0;
            for (let x = len - 1 ; (msg_set[x].createTimeStamp > leaveTimeStamp) || (msg_set[x].createTimeStamp == leaveTimeStamp); --x) {
              ++sum;
            }
            console.log('sum',sum)
            return sum;
          }();
        }
        db.collection('all_user')
        .where({
          _openid: myOpenid,
          'mySession_ids.session_id': sid
        })
        .update({
          data: {
            'mySession_ids.$.unReadNum': parseInt(unReadNum)
          }
        })
        console.log('unReadNum',unReadNum)
      }
      else {
        console.log('会话' + sid + '无新消息');
      }
    }
    let that = this;
    setTimeout(f, 100)
    async function f() {
      await db.collection('all_user')
        .where({
          _openid: myOpenid
        })
        .get()
        .then((res) => {
          if (res.data.length) {
            that.setData({
              sessions: res.data[0].mySession_ids,
            });
            console.log('列表页渲染完成');
          }
        })
      
      if(loading==false){
      wx.hideLoading({
        complete: () => {loading=true},
      })
      }
    }
  },
  //进入会话页
  enterSession(e) {
    console.log('从消息列表页进入会话页');
    var sid = e.currentTarget.dataset.sid;
    var head = e.currentTarget.dataset.head;
    wx.navigateTo({
      url: '/pages/chatManager/chatManager?session_id=' + sid + '&hisUserInfo=' + head,
    })
  },
  onHide: async function () {
    console.log('列表页onhide,关闭监听',watcher);
    if(Object.prototype.toString.call(watcher) === '[object Object]')
    {
     await watcher.close();
     watcher = '';
     console.log('关闭监听watcher')
    }
  },
  onUnload:async function () {
    console.log('onunload 关闭监听');
    if(Object.prototype.toString.call(watcher) === '[object Object]')
    {
     await watcher.close();
     watcher = '';
     console.log('关闭监听watcher')
    }
  },


})